package com.light.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.light.common.enums.DeleteStatusEnum;
import com.light.common.enums.OrderReceiveStatus;
import com.light.common.enums.OrderStatusEnum;
import com.light.common.to.SecKillRabbitTO;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.common.utils.R;
import com.light.common.vo.MemberRespVO;
import com.light.common.vo.WareStockVO;
import com.light.gulimall.order.dao.OrderDao;
import com.light.gulimall.order.dao.OrderItemDao;
import com.light.gulimall.order.dto.SubmitOrderDTO;
import com.light.gulimall.order.entity.OrderEntity;
import com.light.gulimall.order.entity.OrderItemEntity;
import com.light.gulimall.order.feign.CartRemoteServiceClient;
import com.light.gulimall.order.feign.MemberRemoteServiceClient;
import com.light.gulimall.order.feign.ProductRemoteServiceClient;
import com.light.gulimall.order.feign.WareRemoteServiceClient;
import com.light.gulimall.order.interceptor.LoginInterceptor;
import com.light.gulimall.order.service.OrderService;
import com.light.gulimall.order.to.OrderCreateTo;
import com.light.gulimall.order.vo.*;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.light.gulimall.order.constants.OrderConstants.ORDER_TOKEN;


@Slf4j
@Service("orderService")
@RabbitListener(queues = "order.release.order.queue")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberRemoteServiceClient memberRemoteServiceClient;

    @Autowired
    private CartRemoteServiceClient cartRemoteServiceClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WareRemoteServiceClient wareRemoteServiceClient;

    @Autowired
    private ProductRemoteServiceClient productRemoteServiceClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public OrderConfirmVO confirmOrder() {
        log.info("当前主线程:{}", Thread.currentThread().getName());
        OrderConfirmVO vo = new OrderConfirmVO();

        MemberRespVO memberRespVO = LoginInterceptor.threadLocal.get();

        //RequestContextHolder 是线程隔离的，如果在主线程中，其他线程是获取不到的
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressAsync = CompletableFuture.runAsync(() -> {
            log.info("当前addressAsync线程:{}", Thread.currentThread().getName());
            //所以需要在每个子线程中单独塞入requestAttributes
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //收货地址 远程查询会员服务
            //得到用户id
            Long id = memberRespVO.getId();
            R r = memberRemoteServiceClient.infoList(id);
            ObjectMapper objectMapper = new ObjectMapper();
            List<LinkedHashMap> addressEntities = (List<LinkedHashMap>) r.get("addressEntities");
            List<MemberAddressVo> skuSaleAttrValueList = addressEntities.stream()
                    .map(map -> objectMapper.convertValue(map, MemberAddressVo.class))
                    .collect(Collectors.toList());
            vo.setAddresses(skuSaleAttrValueList);
        }, threadPoolExecutor);


        CompletableFuture<Void> cartitemAsync = CompletableFuture.runAsync(() -> {
            log.info("当前cartitemAsync线程:{}", Thread.currentThread().getName());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            Integer integration = memberRespVO.getIntegration();
            //购物车清单 远程调用购物车服务 存在问题，远程调用时其他服务无法感知浏览器请求头信息 解决方案，加上feign配置类
            List<CartItem> currentUserCartItems = cartRemoteServiceClient.getCurrentUserCartItems();
            vo.setOrderItems(currentUserCartItems);
//        可用积分，ums_member 表中的 integration 字段

            vo.setBounds(integration == null ? 0 : integration);

            //订单总额
            BigDecimal orderTotalPrice = BigDecimal.ZERO;
            for (CartItem currentUserCartItem : currentUserCartItems) {
                BigDecimal totalPrice = currentUserCartItem.getTotalPrice();
                orderTotalPrice = orderTotalPrice.add(totalPrice);
            }
            vo.setTotal(orderTotalPrice);

            //应付总额
            vo.setPayPrice(orderTotalPrice);
        }, threadPoolExecutor).thenRunAsync(() -> {
            log.info("当前cartitemAsync.thenRunAsync线程:{}", Thread.currentThread().getName());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<CartItem> orderItems = vo.getOrderItems();
            List<Long> ids = orderItems.stream().map(CartItem::getSkuId).collect(Collectors.toList());
            List<WareStockVO> wareStockVOS = wareRemoteServiceClient.queryWareStock(ids);
            Map<Long, Boolean> map = wareStockVOS.stream().collect(Collectors.toMap(WareStockVO::getSkuId, WareStockVO::getHasStock));
            vo.setHasStock(map);
        });

        try {
            CompletableFuture.allOf(cartitemAsync, addressAsync).get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        vo.setOrderToken(this.makeOrderToken(memberRespVO.getId()));
        return vo;
    }

    /**
     * 提交订单
     * @param dto   前端传递的订单信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//这里的事务仅仅能保证订单数据入表，不能保证远程查库存
//    @GlobalTransactional
    public SubmitOrderResponseVO submitOrder(SubmitOrderDTO dto) {
        log.info("Seata全局事务id=================>{}", RootContext.getXID());
        SubmitOrderResponseVO vo = new SubmitOrderResponseVO();
        //首先进行幂等性校验
        Long result = this.checkIdempotency(dto);
        if (result == 0) {
            vo.setCode(1);
            return vo;
        }

        //组装订单信息
        OrderCreateTo to = this.createOrderInfo(dto);
        //对比金额
        //重新计算后的金额
        BigDecimal payAmount = to.getOrder().getPayAmount();
        //前端传递的金额
        BigDecimal payPrice = dto.getPayPrice();
//        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) >= 0.01) {
//            vo.setCode(2);//验算价格不通过
//            return vo;
//        }

        //保存订单
        this.saveOrderToDB(to);
        //库存锁定
        StockLockVO stockLockVO = new StockLockVO();
        stockLockVO.setOrderSn(to.getOrder().getOrderSn());
        List<CartItem> cartItems = to.getOrderItems().stream().map(orderItemEntity -> {
            CartItem cartItem = new CartItem();
            cartItem.setSkuId(orderItemEntity.getSkuId());
            cartItem.setTitle(orderItemEntity.getSkuName());
            cartItem.setCount(orderItemEntity.getSkuQuantity());
            return cartItem;
        }).collect(Collectors.toList());
        stockLockVO.setCartItems(cartItems);
        //远程调用ware服务
        R r = wareRemoteServiceClient.stockLock(stockLockVO);
        //TODO 手动抛出异常 模拟远程调用成功后本地后续代码又报错的情况（远程数据库操作就不会回滚了）
//        int i = 1 / 0;
        int code = (int) r.get("code");
        if (code != 0) {
            //TODO 锁库存失败 回滚(这里应该手动抛出异常触发submitOrder的本地事务)
            vo.setCode(3);
            return vo;
        }
        //发送消息到order-event-exchange交换机 30分钟后从order.release.order.queue 队列中取消息，判断状态，是否需要关单
        this.releaseOrder(vo.getOrder());
        vo.setCode(0);
        vo.setOrder(to.getOrder());
        return vo;
    }

    @Override
    public void doReleaseOrder(OrderEntity order) {
        Integer status = order.getStatus();
        //需要关单
        if (Objects.equals(status, OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity orderEntityForUpd = new OrderEntity();
            orderEntityForUpd.setId(order.getId());
            orderEntityForUpd.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateById(orderEntityForUpd);
            //order-event-exchange发消息到 stock.release.order.queue 库存服务监听
            //为了防止一种极端情况，就是订单关单由于系统卡顿，一直无法进行关单，库存消息优先到期，判断状态一直解锁不了库存
            //所以在关单之后主动给库存服务发一个消息进行兜底
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", order);
        }
    }

    @Override
    public void createSecKillOrder(SecKillRabbitTO secKillRabbitTO) {
        //TODO 创建秒杀订单...
        log.info("秒杀订单已创建，orderNo：{}",secKillRabbitTO.getOrderNo());
    }

    private void releaseOrder(OrderEntity order) {
        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order);
    }


    private void saveOrderToDB(OrderCreateTo to) {
        //保存订单主表
        save(to.getOrder());
        //保存订单子表 seata 0.7.1 不支持批量
        List<OrderItemEntity> orderItems = to.getOrderItems();
        for (OrderItemEntity orderItem : orderItems) {
            orderItemDao.insert(orderItem);
        }
        ;
    }

    private OrderCreateTo createOrderInfo(SubmitOrderDTO dto) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //组装订单整体信息
        this.createOrder(dto, orderCreateTo);
        //组装具体订单信息
        this.createOrderItems(dto, orderCreateTo);

        //重新计算价格,积分（设置order表的积分和成长值，价格信息）
        this.computePrice(orderCreateTo);


        return orderCreateTo;
    }

    private void computePrice(OrderCreateTo orderCreateTo) {
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        OrderEntity order = orderCreateTo.getOrder();
        BigDecimal itemTotalPrice = BigDecimal.ZERO;
        //商品促销分解金额(所有购物车项目的总计)
        BigDecimal promotionAmount = BigDecimal.ZERO;
        //优惠券优惠分解金额(所有购物车项目的总计)
        BigDecimal couponAmount = BigDecimal.ZERO;
        //积分优惠分解金额(所有购物车项目的总计)
        BigDecimal integrationAmount = BigDecimal.ZERO;
        //总的积分
        Integer integration = 0;
        //总的成长值
        Integer growth = 0;
        for (OrderItemEntity orderItemEntity : orderItems) {
            //这里的RealAmount已经减去各种优惠信息
            itemTotalPrice = itemTotalPrice.add(orderItemEntity.getRealAmount());
            promotionAmount = promotionAmount.add(orderItemEntity.getPromotionAmount());
            couponAmount = couponAmount.add(orderItemEntity.getCouponAmount());
            integrationAmount = integrationAmount.add(orderItemEntity.getIntegrationAmount());
            integration = integration + orderItemEntity.getGiftIntegration();
            growth = growth + orderItemEntity.getGiftGrowth();
        }
        //设置购物车中所有订单的总额
        order.setTotalAmount(itemTotalPrice);
        //应付金额 = 总额+  运费
        order.setPayAmount(itemTotalPrice.add(orderCreateTo.getFare()));
        //促销优化金额
        order.setPromotionAmount(promotionAmount);
        //优惠券抵扣金额
        order.setCouponAmount(couponAmount);
        //积分抵扣金额
        order.setIntegrationAmount(integrationAmount);
        //积分
        order.setIntegration(integration);
        //成长值
        order.setGrowth(growth);


    }

    private OrderCreateTo createOrderItems(SubmitOrderDTO dto, OrderCreateTo orderCreateTo) {
        //查询购物车中的信息
        List<CartItem> currentUserCartItems = cartRemoteServiceClient.getCurrentUserCartItems();
        List<OrderItemEntity> orderItemEntities = currentUserCartItems.stream().map(cartItem -> {
            return bulidItems(orderCreateTo, cartItem);
        }).collect(Collectors.toList());


        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    private OrderItemEntity bulidItems(OrderCreateTo orderCreateTo, CartItem cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderId(orderCreateTo.getOrder().getId());
        orderItemEntity.setOrderSn(orderCreateTo.getOrder().getOrderSn());
        //组装sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        //单价
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        //数量
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        orderItemEntity.setSkuAttrsVals(String.join(";", cartItem.getSkuAttr()));
        //组装spu信息
        SpuInfoVO spuInfo = productRemoteServiceClient.getSpuInfo(cartItem.getSkuId());
        orderItemEntity.setSpuPic(spuInfo.getSpuPic());
        orderItemEntity.setSpuName(spuInfo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfo.getSpuBrand());
        orderItemEntity.setCategoryId(spuInfo.getCategoryId());

        //组装积分信息 单个的积分 * 件数
        orderItemEntity.setGiftIntegration(cartItem.getTotalPrice().multiply(BigDecimal.valueOf(cartItem.getCount())).intValue());
        orderItemEntity.setGiftGrowth(cartItem.getTotalPrice().multiply(BigDecimal.valueOf(cartItem.getCount())).intValue());

        //商品促销分解金额
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        //优惠券优惠分解金额
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        //积分优惠分解金额
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        //该商品经过优惠后的分解金额 单价 * 数量
        BigDecimal amount = cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getCount()));
        amount = amount.subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(amount);

        return orderItemEntity;
    }

    private OrderCreateTo createOrder(SubmitOrderDTO dto, OrderCreateTo orderCreateTo) {
        MemberRespVO memberRespVO = LoginInterceptor.threadLocal.get();
        LoginInterceptor.threadLocal.remove();//防止内存泄漏
        OrderEntity orderEntity = new OrderEntity();
        //设置订单号
        orderEntity.setOrderSn(IdWorker.getTimeId());
        //设置用户id
        orderEntity.setMemberId(memberRespVO.getId());
        //设置用户名
        orderEntity.setMemberUsername(memberRespVO.getUsername());
        //设置运费
        FareVo fare = wareRemoteServiceClient.getFare(dto.getAddrId());
        orderEntity.setFreightAmount(fare.getFare());
        orderCreateTo.setFare(fare.getFare());
        //设置收货地址信息
        orderEntity.setReceiverName(fare.getAddressVo().getName());
        orderEntity.setReceiverPhone(fare.getAddressVo().getPhone());
        orderEntity.setReceiverPostCode(fare.getAddressVo().getPostCode());
        orderEntity.setReceiverProvince(fare.getAddressVo().getProvince());
        orderEntity.setReceiverCity(fare.getAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fare.getAddressVo().getDetailAddress());
        orderEntity.setReceiverRegion(fare.getAddressVo().getRegion());

        //收货状态未确认
        orderEntity.setConfirmStatus(OrderReceiveStatus.NOT_CONFIRM.getCode());
        //删除状态未删除
        orderEntity.setDeleteStatus(DeleteStatusEnum.NO.getCode());
        //订单状态代付款
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //自动收货时间
        orderEntity.setAutoConfirmDay(7);

        //设置修改时间
        orderEntity.setModifyTime(new Date());
        orderCreateTo.setOrder(orderEntity);
        return orderCreateTo;

    }

    private Long checkIdempotency(SubmitOrderDTO dto) {
        MemberRespVO memberRespVO = LoginInterceptor.threadLocal.get();
        //前端传递的orderToken
        String orderToken = dto.getOrderToken();
        //把比较和删除放在一条命令里，保证原子性
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        return stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(ORDER_TOKEN + memberRespVO.getId()), orderToken);

    }

    private String makeOrderToken(Long id) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(ORDER_TOKEN + id, uuid, 30, TimeUnit.MINUTES);
        return uuid;
    }

}